package com.scau.yangsuiyu.estore.dababases.dao;

import com.scau.yangsuiyu.estore.dababases.entity.Category;
import com.scau.yangsuiyu.estore.dababases.entity.Category;
import com.scau.yangsuiyu.estore.dababases.entity.Goods;
import com.scau.yangsuiyu.estore.util.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;

import java.util.List;

/**
 * @author suiyu_yang
 * @description 类别的Dao
 * @date 2019-06-10 12:42
 * @email suiyu_yang@163.com
 */
public class CategoryDao {

    public void insert(Category category) {
        Session session = HibernateUtil.currentSession();
        Transaction transaction = session.beginTransaction();

        session.save(category);

        transaction.commit();
        HibernateUtil.closeSession();
    }

    public void delete(Category category) {
        Session session = HibernateUtil.currentSession();
        Transaction transaction = session.beginTransaction();

        session.delete(category);

        transaction.commit();
        HibernateUtil.closeSession();
    }

    public void update(Category category) {
        Session session = HibernateUtil.currentSession();
        Transaction transaction = session.beginTransaction();

        session.update(category);

        session.flush();
        transaction.commit();
        HibernateUtil.closeSession();
    }

    public List<Category> getAllCategory() {
        List<Category> result;

        Session session = HibernateUtil.currentSession();

        String sql = "from Category category";

        result = session.createQuery(sql).list();

        HibernateUtil.closeSession();
        return result;
    }

    public Category getCategoryByName(String categoryName) {
        Session session = HibernateUtil.currentSession();

        String sql = "from Category category where category.name = '" + categoryName + "' ";

        Category category = (Category) session.createQuery(sql).uniqueResult();

        HibernateUtil.closeSession();
        return category;
    }

    public List<String> getAllCategoryName() {
        List<String> result;

        Session session = HibernateUtil.currentSession();
        String sql = "select name from Category";

        result = session.createQuery(sql).list();

        return result;
    }
}
